package com.crm.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crm.common.annotation.Log;
import com.crm.common.enums.BusinessType;
import com.crm.common.result.AjaxResult;
import com.crm.domain.Rule;
import com.crm.service.RuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/rule")
@RequiredArgsConstructor
@Slf4j
public class RuleController {

    private final RuleService ruleService;

    private final RedisTemplate redisTemplate;

    /**
     * 规则列表查询
     * @param type
     * @return
     */
    @GetMapping("/list/{type}")
    @Log(title = "规则管理", businessType = BusinessType.EXPORT)
    public AjaxResult listRule(@PathVariable String type){
        List<Rule> ruleList = ruleService.list(Wrappers.<Rule>lambdaQuery().eq(Rule::getType, type));
        return AjaxResult.success(ruleList);
    }


    /**
     * 根据type查询池配置
     * @param type
     * @return
     */
    @GetMapping("/pool/{type}")
    public AjaxResult getRuleByType(@PathVariable String type){
        log.info("当前规则类型: {}",type);
        Rule rule = ruleService.getOne(Wrappers.<Rule>lambdaQuery().eq(Rule::getType, type));
        return AjaxResult.success(rule);
    }

//    @PostMapping("/pool")
//    public AjaxResult saveRule(@RequestBody Rule rule){
//        redisTemplate.opsForValue().set(Rule.MAX_NUMBER_KEY+rule.getType(),rule.getMaxNunmber());
//        ruleService.save(rule);
//        return AjaxResult.success();
//    }

    @PutMapping("/pool")
    public AjaxResult updateRule(@RequestBody Rule rule){
        redisTemplate.opsForValue().set(Rule.MAX_NUMBER_KEY+rule.getType(),rule.getMaxNunmber());
        Integer o = (Integer)redisTemplate.opsForValue().get(Rule.MAX_NUMBER_KEY + rule.getType());
        log.info("最大持有量: {}",o);
        ruleService.updateById(rule);
        return AjaxResult.success();
    }
}
